package com.java2007.controller;

import com.alibaba.druid.util.StringUtils;
import com.java2007.constant.ServletConstant;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 通用Servlet
 * @author ZOU
 */

@WebServlet("/baseServlet")

public class BaseServlet extends HttpServlet {

    /**
     * 无论什么请求都会有service去解决
         * 一、反射获取方法执行
             * 1.通过类名获取类对象
             * 2.类对象拿到方法名
             * 3.方法.invoked调用方法（传调用对象this，形参）
     *
     * @param req
     * @param res
     * @throws ServletException
     * @throws IOException
     */

    @Override

    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        try {
            String methodist = request.getParameter(ServletConstant.METHOD);
            if (StringUtils.isEmpty(methodist)){
                response.sendRedirect(request.getContextPath()+"/index.jsp");
                return;
            }
            //通过当前对象this获得类对象clazz
            Class<?> clazz = this.getClass();
            //通过类对象获取方法（这里还要看方法是否是private，需不需要暴力破解，否则无法获取）, 类对象.getMethod（方法名，形参类型）
            Method method = clazz.getMethod(methodist, HttpServletRequest.class, HttpServletResponse.class);
            //方法调用  方法名.invoke(调用对象，形参)
            Object object = method.invoke(this, request, response);


            if (object != null) {
                String result = (String) object;
                String url = null;
                //将返回值进行分割，取URL
                url = result.substring(result.indexOf(ServletConstant.SEG) + 1);
                //判断是重定向还是转发
                if (result.startsWith(ServletConstant.FORWARD)) {
                    request.getRequestDispatcher(url).forward(request, response);
                } else if (result.startsWith(ServletConstant.REDIRECT)) {
                    response.sendRedirect(request.getContextPath() + url);
                } else {
                    response.getWriter().write(result);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("ServletConstant.COMMON_ERROR_MESSAGE");
        }
    }
}
